package com.zlm.service.impl;

import com.zlm.constants.SysConstants;
import com.zlm.domain.ResponseResult;
import com.zlm.domain.entity.LoginUser;
import com.zlm.domain.entity.User;
import com.zlm.domain.vo.UserInfoVo;
import com.zlm.domain.vo.UserLoginVo;
import com.zlm.service.BlogLoginService;
import com.zlm.utils.BeanCopyUtils;
import com.zlm.utils.JwtUtil;
import com.zlm.utils.RedisCache;
import com.zlm.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * @author zlm
 * @date 2024/12/10
 */
@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(authenticate==null){
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userId生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String token = JwtUtil.createJWT(id.toString());
        //存入redis
        redisCache.setCacheObject(SysConstants.LOGIN_TOKEN_KEY_PRE +id,loginUser);
        //封装数据
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setToken(token);
        userLoginVo.setUserInfo(userInfoVo);

        return ResponseResult.okResult(userLoginVo);
    }

    @Override
    public ResponseResult logout() {
        //删除redis中的用户信息
        Long id = SecurityUtils.getUserId();
        redisCache.deleteObject(SysConstants.LOGIN_TOKEN_KEY_PRE +id);

        return ResponseResult.okResult();
    }
}
